package dyy.zc.campuspay.ui.fragment;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;


import java.io.File;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.campuspay.R;
import dyy.zc.campuspay.application.MyApplication;
import dyy.zc.campuspay.base.BaseFragment;
import dyy.zc.campuspay.bean.Account;
import dyy.zc.campuspay.permission.PermissionsActivity;
import dyy.zc.campuspay.permission.PermissionsChecker;
import dyy.zc.campuspay.ui.activity.ChangeRealNameActivity;
import dyy.zc.campuspay.ui.activity.LoginActivity;
import dyy.zc.campuspay.ui.activity.ReChargeActivity;
import dyy.zc.campuspay.ui.activity.ReseivePasswordActivity;
import dyy.zc.campuspay.utils.AppManager;
import dyy.zc.campuspay.utils.BmobUtils;
import dyy.zc.campuspay.utils.ImageLoaderUtils;
import dyy.zc.campuspay.utils.ImageUploadUtil;
import dyy.zc.campuspay.utils.ImageUtil;
import dyy.zc.campuspay.utils.ToastUtils;
import dyy.zc.campuspay.utils.Utils;
import dyy.zc.campuspay.views.ActionSheet;
import dyy.zc.campuspay.views.CircleImageView;
import dyy.zc.campuspay.views.MyAlertDialog;

/**
 * 我的主页
 * Created by chuan on 2017/3/9.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener, ActionSheet.OnSheetItemClickListener {
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    };
    public static int type = 0;
    //拍照、从相册选择、照片保存成功
    private final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2, SAVE_IMAGE_SUCCESS = 3;
    private final int REQUEST_CODE = 0;
    private TextView loginOut;
    private RelativeLayout chongzhi;
    private TextView tv_realName;//真实姓名
    private TextView tv_nikeName;//昵称
    private TextView tv_title;//标题
    private TextView remain;
    private RelativeLayout back;
    private TextView phone;//绑定手机
    private RelativeLayout rl_realName;//真实姓名rl
    private RelativeLayout rl_reseivePassword;//修改密码rl
    private String[] items = {"拍照", "我的相册"};
    // 头像文件、上传头像的名称、本地图片uri
    private File imageFile;
    private Uri imageUri; // 图片路径
    public static CircleImageView civ_head;
    private String saveFileName = "";
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    private BmobUtils bmobUtils;
    public Account account;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1){
                initInfo(account);
            }
        }
    };
    @Override
    protected View onCreateViews(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        findViewsByIds(view);
        bind();
        initData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume","onResume");
        bmobUtils.getUserInfo(loginuser.getAccount(),1,handler);
//        initInfo();
    }

    public void initInfo(Account account){
//        loginuser = MyApplication.getInstance().readLoginUser();
        if (account.getHead()!=null){
            ImageLoaderUtils.initImage(getActivity(),
                    account.getHead().getFileUrl(), civ_head, R.mipmap.ic_launcher);
        }else {
            civ_head.setImageResource(R.mipmap.ic_launcher);
        }
        phone.setText(account.getAccount());
        //Log.e("onResume","first");
        tv_nikeName.setText(account.getNikeName());
        tv_realName.setText(account.getRealName());
        if (account.getRemain() == null){
            remain.setText("¥ 0.00");
        }else {
            remain.setText("¥ "+account.getRemain()+"");
        }

    }

    private void initData() {
        bmobUtils = new BmobUtils(getActivity());
        tv_title.setText("个人信息");
        back.setVisibility(View.GONE);
    }

    private void bind() {
        civ_head.setOnClickListener(this);
        loginOut.setOnClickListener(this);
        chongzhi.setOnClickListener(this);
        rl_realName.setOnClickListener(this);
        tv_nikeName.setOnClickListener(this);
        rl_reseivePassword.setOnClickListener(this);
    }

    private void findViewsByIds(View view) {
//        // 缺少权限时, 进入权限配置页面
//        mPermissionsChecker = new PermissionsChecker(getActivity());
//        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
//            startPermissionsActivity();
//        }
        back = Utils.findViewsById(view, R.id.top_rl_back);
        phone = Utils.findViewsById(view,R.id.myInfo_tv_changePhone);
        loginOut = Utils.findViewsById(view,R.id.loginOut);
        chongzhi = Utils.findViewsById(view,R.id.myInfo_rl_personalDescribe);
        civ_head = Utils.findViewsById(view, R.id.myInfo_civ_head);
        tv_title = Utils.findViewsById(view, R.id.top_tv_title);
        tv_nikeName = Utils.findViewsById(view, R.id.myInfo_tv_nikeName);
        rl_realName = Utils.findViewsById(view, R.id.myInfo_rl_realName);
        tv_realName = Utils.findViewsById(view, R.id.myInfo_tv_realName);
        rl_reseivePassword = Utils.findViewsById(view, R.id.myInfo_rl_revisePassword);
        remain = Utils.findViewsById(view, R.id.myInfo_tv_remain);
    }
    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(getActivity(), REQUEST_CODE, PERMISSIONS);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.myInfo_civ_head://修改头像
                showActionSheetDialog(items);
                break;
            case R.id.loginOut://退出登录
                logoutDialog();
                break;
            case R.id.myInfo_rl_personalDescribe://充值
                startActivity(new Intent(getActivity(), ReChargeActivity.class));
                break;
            case R.id.myInfo_rl_realName://修改真实姓名
                Intent intent = new Intent(getActivity(), ChangeRealNameActivity.class);
                intent.putExtra("real", tv_realName.getText().toString());
                intent.putExtra("title", "修改真实姓名");
                type = 1;
                startActivityForResult(intent, 222);
                break;
            case R.id.myInfo_tv_nikeName://修改昵称
                Intent intent1 = new Intent(getActivity(), ChangeRealNameActivity.class);
                intent1.putExtra("real", tv_nikeName.getText().toString());
                intent1.putExtra("title", "修改昵称");
                type = 0;
                startActivityForResult(intent1, 222);
                break;
            case R.id.myInfo_rl_revisePassword://修改密码
                Intent intent2 = new Intent(getActivity(), ReseivePasswordActivity.class);
                intent2.putExtra("title", "修改密码");
                startActivityForResult(intent2, 333);
                break;
        }
    }

    //头像选择对话框
    private void showActionSheetDialog(String[] items) {
        ActionSheet actionSheet = new ActionSheet(getActivity())
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (int i = 0; i < items.length; i++) {
            actionSheet.addSheetItem(items[i], ActionSheet.SheetItemColor.Blue, MineFragment.this);
        }
        actionSheet.show();

    }

    /**
     * 退出登录提示框
     */
    private void logoutDialog() {
        MyAlertDialog logDialog = new MyAlertDialog(getActivity());
        logDialog.builder()
                .setTitle("退出提示")
                .setMsg("是否要退出登录？")
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplication.getInstance().saveUserInfo(null);
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                        AppManager.getInstance().finishActivity();
                    }
                })
                .show();
    }

    @Override
    public void onClick(int which) {
        switch (which) {
            case TAKE_PHOTO:
                //拍照
                imageFile = ImageUploadUtil.createImageFile(ImageUploadUtil.CAMERA_SAVEDIR2, ImageUploadUtil.createImageName());
                startActivityForResult(ImageUploadUtil.intentImageCapture(imageFile), ImageUploadUtil.TAKE_PHOTO);
                break;
            case CHOOSE_PHOTO:
                //从相册选择
                startActivityForResult(ImageUtil.intentChooseImg(),
                        CHOOSE_PHOTO);
                break;
        }
    }

    /**
     * Activity回调事件处理
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == 0) {
                    return;
                }
                //拍照
                ImageUtil.paizhaocreateImagefile(getActivity(), imageFile);
                if (imageFile == null) {
                    ToastUtils.shortToast(getActivity(), "图片太大无法上传");
                    return;
                }
                doSendThread();//上传图片
                break;
            case CHOOSE_PHOTO:
                //相册
                if (resultCode == 0) return;
                imageUri = data.getData();
                imageFile = MyApplication.getInstance().createimagefile(imageUri, getVmWidth(), getVmHeight());
                if (imageFile == null) {
                    ToastUtils.shortToast(getActivity(), "imageFile为空2");
                    return;
                }
                doSendThread();//上传图片
                break;
            case 222:
                if (data !=null){
                    String str = data.getStringExtra("name");
                    //Log.e("name",str+"");
                    if (type == 1) {
                        tv_realName.setText(str);
                    } else {
                        tv_nikeName.setText(str);
                    }
                }


                break;
        }
    }

    /**
     * 上传头像
     */
    private void doSendThread() {
        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
        civ_head.setImageBitmap(bitmap);
        BmobFile bmobFile = new BmobFile(imageFile);
        bmobUtils.upLoadFile(bmobFile,imageFile);
        //initInfo();
    }

}
